$( function() {

    let audit = new Audit({
        voucher_store_name   : '2011年.xls',
        initial_balance_name : '2011年科目余额表.xls',
        from_date            : new Date('2011-01-01'),
        to_date              : new Date('2012-01-01'),
    })
	var trial_balances

	// ready start.
    audit.ready( self => {

		// date element init
		$('[name="from_date"]')[0].valueAsDate = self.from_date
		$('[name="from_date"]').on( 'input', (e) => {
			self.from_date = new Date( $('[name="from_date"]').val() )
		})
		$('[name="to_date"]')[0].valueAsDate = self.to_date
		$('[name="to_date"]').on( 'input', (e) => {
			self.to_date = new Date( $('[name="to_date"]').val() )
		})

		// list accounts
		self.get_all_accounts().then( (accounts) => {
			accounts.forEach( (v, i) => {
				$('#accounts').append(
					$('<p>')
						.addClass('account')
						.attr({
							'data-code': v.code,
							'data-name': v.name,
						})
						.text(v.code + ' - ' + v.name)
				)
			})
		})

		///////////////////////////////////////////////////////////////////////////////
		//
		// Events
		//
		///////////////////////////////////////////////////////////////////////////////

        // generate trial balance    
        $('#trial_balance').on( 'click', async function() {
			if(!trial_balances) {
				trial_balances = await self.generate_trial_balance()
			}
			process_trial_balance(trial_balances)
        })

		// get balance sheet
        $('#balance_sheet').on( 'click', async function() {
			if(!trial_balances) {
				trial_balances = await self.generate_trial_balance()
			}
			process_balance_sheet(trial_balances)
        })

		// delete database button
		$('#delete_database').on( 'click', function() {
			self.delete_db()
			window.location.reload()
		})

		// furtured elements: get detail_account
		$(document).on('click', '.account', async function() {
			var vouchers = await self.get_voucher_from_recurse_accounts( 
				$(this).data('code').toString(), self.from_date, self.to_date)
			process_detail_account(self, vouchers)
		})

		$('#export_sheet_test').on( 'click', async function() {
			var header = [
				['科目审定表',,,,,,,,,,,],
				[,,,,,,,,,'索引号：','ZA-1'],
				['单位名称:',,,,'编制人:',,,,,'编制日期:',],
				['截止日期:',,,,'复核人:',,,,,'复核日期:',],
				['科目代码', '科目名称', '项目名称', '期末',   '账项调整',,    '重分类调整',,  '期末',   '上期末', '索引号'],
				['科目代码', '科目名称', '项目名称', '未审数', '借方', '贷方', '借方', '贷方', '审定数', '审定数'],	
			]

			var footer = [
				['审核说明:', '∧、＜、B、T、G、S、T/B'],
				['审核结论:', '调整后本期末审定数可以确认。审核结论:未见重大异常，本期末审定数可以确认。']
			]

			/*
			var export_sheet_test = header.concat(display_accounts).concat(footer)

			var container = document.getElementById('grid')
			var grid = new Handsontable(container, {
				rowHeaders: true,
				data: export_sheet_test,
				mergeCells: [
                    {row:0, col:0, rowspan:1, colspan:11},
                    {row:4, col:0, rowspan:2, colspan:1},
                    {row:4, col:1, rowspan:2, colspan:1},
                    {row:4, col:2, rowspan:2, colspan:1},
                    {row:4, col:4, rowspan:1, colspan:2},
                    {row:4, col:6, rowspan:1, colspan:2},
                    {row:6+display_accounts.length, col:1, rowspan:1, colspan:2},
                    {row:7+display_accounts.length, col:1, rowspan:1, colspan:5},
                ],
				colWidths: 80,
				readOnly: true,
			})
			*/

			/////////////////////////////////////////////
			//
			var as_102 = await self.get_account_children("102")
			var d_102 = []
			as_102.forEach(function(item, index) {
				d_102.push([ item.code, item.name, '', item.closing_debit - item.closing_credit, ])
			})

			var as_203 = await self.get_account_children("203")
			var d_203 = []
			as_203.forEach(function(item, index) {
				d_203.push([ item.code, item.name, '', item.closing_debit - item.closing_credit, ])
			})

			/* Generate Workbook */
			var wb = XLSX.utils.book_new()
			var ws = XLSX.utils.aoa_to_sheet(header.concat(d_102).concat(footer))
			XLSX.utils.book_append_sheet(wb, ws, "d_102")

			ws = XLSX.utils.aoa_to_sheet(header.concat(d_203).concat(footer))
			XLSX.utils.book_append_sheet(wb, ws, "d_203")

			/* Trigger Download with `writeFile` */
			XLSX.writeFile(wb, "audit.xls", {compression:true})
		})

    }) // end ready.
})

let process_detail_account =
	(self, vouchers) => {
		var display_vouchers = new Array;
		
		vouchers.forEach(function(item, index) {
			display_vouchers.push([
				item.account_code,
				item.account,
				item.slug,
				item.debit,
				item.credit,
				item.date,
				item.comment == null ? '' : item.comment
			])
		})

		$("#grid").empty()
		var container = document.getElementById('grid')
		var grid = new Handsontable(container, {
			data: display_vouchers,
			rowHeaders: true,
			minSpareRows: 1,
			startRows: 5,
			startCols: 5,
			minSpareRows: 1,
			readOnly: true,
			colHeaders: ['科目代码', '科目名称', '凭证号', '借方', '贷方', '日期', '备注'],
			columns: [
				{}, {}, {},
				{
				  type: 'numeric',
				  numericFormat: {
					pattern: '$0,0.00',
					culture: 'zh-CN' // this is the default culture, set up for USD
				  },
				},
				{
				  type: 'numeric',
				  numericFormat: {
					pattern: '$0,0.00',
					culture: 'zh-CN' // this is the default culture, set up for USD
				  },
				},
				{
				  type: 'date',
				  dateFormat: 'MM/DD/YYYY',
				  correctFormat: true,
				  defaultDate: '01/01/1900',
				},
				{}
			],
			afterSelection: async function(row, column, row2, column2, preventScrolling, selectionLayerLevel) {
				// setting if prevent scrolling after selection
				preventScrolling.value = true
				var slug = display_vouchers[row][2]
				var date = display_vouchers[row][5]
				var sub_vouchers = await self.get_voucher_by_slug_date(slug, new Date(date)) 

				var display_sub_vouchers = new Array;
			
				sub_vouchers.forEach(function(item, index) {
					display_sub_vouchers.push([
						item.account_code,
						item.account,
						item.slug,
						item.debit,
						item.credit,
						item.date,
						item.comment == null ? '' : item.comment
					])
				})

				var container2 = document.getElementById('sub-grid')
				$('#sub-grid').text('Loading...')

				$('#detailModal').on('shown.bs.modal', function () {
					$('#sub-grid').empty()
					var grid2 = new Handsontable(container2, {
						data: display_sub_vouchers,
						rowHeaders: true,
						minSpareRows: 1,
						startRows: 5,
						startCols: 5,
						minSpareRows: 1,
						readOnly: true,
						colHeaders: ['科目代码', '科目名称', '凭证号', '借方', '贷方', '日期', '备注'],

					})
				})
				$('#detailModal').modal('show')
			},		
		})
	}


let process_trial_balance = 
	(balances) => {
		// Array deepcopy
		var trial_balances = JSON.parse(JSON.stringify(balances))

		const trial_balance_titles = [
			'科目代码', '科目名称', '期初借方余额', '期初贷方余额', 
			'本期借方发生额', '本期贷方发生额', '期末借方余额', '期末贷方余额'
		]

		// format value.
		trial_balances.forEach(function(item, index, array){
			for( var i = 0; i < item.length; i++ ) {
				if( typeof item[i] === 'number' )
					item[i] = Number(item[i]).formatMoney()
			}
		});
		trial_balances = [trial_balance_titles].concat(trial_balances)

		// write jexcel
		$('#grid').jexcel({ data:trial_balances, colWidths: [100,300, 100,100,100,100,100,100,] })
	}

let process_balance_sheet =
	(balances) => {
		// Array deepcopy
		var balance_sheet = JSON.parse(JSON.stringify(balances))

		const trial_balance_titles = [
			'科目代码', '科目名称', '期初余额', '期末余额'
		]

		balance_sheet = balance_sheet.filter( 
			e => { return e[0].split('.').length == 1 }
		)
		balance_sheet.forEach(function(item, index, array){
			var remove_indexes = [3,4,5,7];
			item[2] -= item[3];
			item[6] -= item[7];
			item.splice(3,3);
			item.splice(-1,1);
		})

		// format value.
		balance_sheet.forEach(function(item, index, array){
			for( var i = 0; i < item.length; i++ ) {
				if( typeof item[i] === 'number' )
					item[i] = Number(item[i]).formatMoney()
			}
		});
		balance_sheet = [trial_balance_titles].concat(balance_sheet)

		// write jexcel
		$('#grid').jexcel({ data:balance_sheet, colWidths: [100,300, 100,100,100,100,100,100,] })
	}
